package main;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Set;

public class MapProp {
	private static Properties mapProp;

	/**
	 * Read constants and parameters from default.properties file and overwite
	 * them with current.properties if needed
	 * 
	 * @throws IOException
	 */
	public static void load() throws IOException {
		// create and load default properties
		mapProp = new Properties();
		try (FileInputStream in = new FileInputStream("maps.properties")) {
			mapProp.load(in);
			in.close();
		}
	}
	
	/**
	 * Return a list of coupled fileID/fileName
	 * 
	 * @param key
	 *            : propertie name
	 * @return List of propertie values (file name;file number)
	 */
	
		public static List <MapFile> getMapFiles(String key) {
			String tmp=mapProp.getProperty(key);
			List <MapFile> result=null;
			if (tmp != null) {
				result = new ArrayList<>();
				String [] tab=tmp.split(";");
				for (String s : tab) {
					String [] tab2=s.split(",");
					int num=Integer.parseInt(tab2[1]);
					MapFile file=new MapFile(tab2[0],num);
					result.add(file);
				}
			}
			return result;
		}
		
		/**
		 * Return the filename of the ID file for the map key
		 * 
		 * @param key
		 *            : map name
		 * @return List of propertie values (file name;file number)
		 */
		
			public static String getMapFileName(String key, int number) {
				String fileName="";
				String tmp=mapProp.getProperty(key);
				List <MapFile> result=null;
				if (tmp != null) {
					result = new ArrayList<>();
					String [] tab=tmp.split(";");
					for (String s : tab) {
						String [] tab2=s.split(",");
						int num=Integer.parseInt(tab2[1]);
						MapFile file=new MapFile(tab2[0],num);
						if (file.getFileNumber()==number) {
							fileName=file.getFileName();
						}
					}
				}
				return fileName;
			}	
		
		/**
		 * 
		 * @return the keys of the propertie
		 */
		
			public static String[] getMapkeys() {

				Set<Object> keys = mapProp.keySet();
				String[] result=new String[mapProp.size()];
				int i=0;
				for (Object mapName : keys) {
					result[i++]=mapName.toString();
				}
				return result;
			}
			
			/**
			 * return a list of 
			 * @param key
			 * @param airfieldOnly
			 * @return
			 */
			public static List <Integer> getMapfileID(String key, boolean airfieldOnly) {
				List <Integer> result=new ArrayList<>();
				List <MapFile>fileList=MapProp.getMapFiles(key);
				for (MapFile file : fileList) {
					String name=file.getFileName();
					if (!airfieldOnly || (airfieldOnly && name.contains("Base-no-trunc"))) {
						int tmp=file.getFileNumber();
						result.add(tmp);
					}
				}
				return (result);
			}
		
}
